package com.jml.zookeeper.一期.zookeeper分布式锁;

import org.I0Itec.zkclient.IZkDataListener;
import java.util.concurrent.CountDownLatch;

//这个类必须是多例的，否则countDownLatch存在线程安全问题
public class ZookeeperDistrbuteLock extends ZookeeperAbstractLock {
	private CountDownLatch countDownLatch = null;

	@Override
	public boolean tryLock() {
		try {
			//创建临时节点
			zkClient.createEphemeral(PATH);
			return true;
		} catch (Exception e) {
			//创建临时节点失败
			return false;
		}
	}

	@Override
	public void waitLock() {
		IZkDataListener izkDataListener = new IZkDataListener() {
			//监听事件节点被删除
			@Override
			public void handleDataDeleted(String path) throws Exception {
				// 唤醒被等待的线程
				if (countDownLatch != null) {
					countDownLatch.countDown();
				}
			}
			//监听事件节点被修改
			public void handleDataChange(String path, Object data) throws Exception {

			}
		};

		// 注册事件
		zkClient.subscribeDataChanges(PATH, izkDataListener);

		if (zkClient.exists(PATH)) {
			countDownLatch = new CountDownLatch(1);
			try {
				countDownLatch.await();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		// 删除监听
		zkClient.unsubscribeDataChanges(PATH, izkDataListener);
	}

}

